<template>
  <!-- 原生组件解决弹框还能滚动的问题 -->
  <!-- #ifdef APP-PLUS -->
  <page-meta :page-style="popupVisible ? 'overflow:hidden' : 'overflow:auto'"></page-meta>
  <!-- #endif -->
  <view class="container">
    <template v-if="permission.shortOrder || permission.longOrder">
      <ShortOrderList
        ref="shortOrderListRef"
        :permission="permission"
        @tabClicked="orderTabChange"
        @popupVisible="popupVisibleFn"
        v-if="permission.shortOrder && lazyLoadTabs['short-order']"
        v-show="activeTab == 'short-order'"
      />
      <LongOrderList
        ref="longOrderListRef"
        :permission="permission"
        @tabClicked="orderTabChange"
        @popupVisible="popupVisibleFn"
        v-if="permission.longOrder && lazyLoadTabs['long-order']"
        v-show="activeTab == 'long-order'"
      />

      <!-- 创建订单 -->
      <DragButton v-if="showCreateBtn" @click="createOrderFn">
        <view>代客<view>下单</view></view>
      </DragButton>
      <!-- 返回顶部按钮 -->
      <TopButton :scrollTop="scrollTop" />
    </template>
    <ve-empty v-else class="auth-empty" :marginTop="0" type="auth" text="暂未菜单权限" />
  </view>
</template>

<script setup>
  import { ref, computed, nextTick, onMounted } from 'vue'
  import { onLoad, onPageScroll, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
  import { userStore } from '@/stores'
  import { appConfig } from '@/config/index.js'
  import { usePermission } from '@/hooks/usePermission'
  import DragButton from '@/components/drag-button.vue'
  import TopButton from '@/components/top-button.vue'
  import ShortOrderList from './short-order/list.vue'
  import LongOrderList from './long-order/list.vue'
  // TODO
  import { listStore } from '@/stores'
  import { useBindEventOn } from '@/hooks/useListNavigate'

  const userInfoStore = userStore()
  const listQueryStore = listStore()

  // 懒加载, false未加载
  const lazyLoadTabs = ref({
    'short-order': false,
    'long-order': false,
  })
  // 长短租list ref
  const shortOrderListRef = ref()
  const longOrderListRef = ref()
  // 是否展开了popup
  const popupVisible = ref(false)
  const popupVisibleFn = (status) => {
    popupVisible.value = status
  }
  // 当前选中的tab
  const activeTab = computed(() => {
    return listQueryStore.orderActiveTab
  })

  // 记录滚动位置，切换时保持滚动的位置
  const scrollPosition = {
    'short-order': 0,
    'long-order': 0,
  }
  const scrollTop = ref(0)
  // 监听滚动事件
  onPageScroll((e) => {
    scrollTop.value = e.scrollTop
  })

  // 切换长短租
  const orderTabChange = (type) => {
    // 切换后同步 搜索keyword
    // if (type == 'long-order') {
    //   listQueryStore.lOrderQueryParam.keywords = listQueryStore.sOrderQueryParam.keywords
    // } else {
    //   listQueryStore.sOrderQueryParam.keywords = listQueryStore.lOrderQueryParam.keywords
    // }
    // 记录当前tab的滚动位置
    scrollPosition[activeTab.value] = scrollTop.value
    // 修改activedTab的值
    listQueryStore.updateOrderActiveTab(type)
    // 懒加载是否加载设置true
    lazyLoadTabs.value[activeTab.value] = true
    // 滚动到之前的记录的位置
    nextTick(() => {
      uni.pageScrollTo({
        scrollTop: scrollPosition[type],
        duration: 0,
      })
    })
  }

  // 是否显示新增按钮；业务开关仅影响新增按钮不影响列表展示
  const showCreateBtn = computed(() => {
    if (activeTab.value == 'short-order') {
      return permission.value.shortOrderOpen && permission.value.shortOrderAdd
    }
    return permission.value.longOrderOpen && permission.value.longOrderAdd
  })
  // 创建订单
  const createOrderFn = () => {
    if (activeTab.value == 'short-order') {
      shortOrderListRef.value.createOrderFn()
      return
    }
    longOrderListRef.value.createOrderFn()
  }

  // 长短租页面权限
  const permission = ref({
    // 列表权限
    shortOrder: true,
    longOrder: true,
    // 是否开启业务；
    shortOrderOpen: true,
    longOrderOpen: true,
    // 新增按钮权限
    shortOrderAdd: true,
    longOrderAdd: true,
  })
  // 监听子页面（交车、还车等业务完成）

  // 获取权限
  const getPermission = () => {
    if (appConfig.asyncRoutes == false) {
      lazyLoadTabs.value['short-order'] = true
      return
    }
    userInfoStore.setEpDetail(false).then(() => {
      // 列表权限
      permission.value.shortOrder = usePermission('svmsapp:order:short-order')
      permission.value.longOrder = usePermission('svmsapp:order:long-order')
      // 是否开启业务
      permission.value.shortOrderOpen = userInfoStore.epServiceIncludeShortOrder
      permission.value.longOrderOpen = userInfoStore.epServiceIncludeLongOrder
      // 按钮
      permission.value.shortOrderAdd = usePermission('svmsapp:order:short-order.create')
      permission.value.longOrderAdd = usePermission('svmsapp:order:long-order.create')

      // 有长租或者短租的列表权限
      if (permission.value.shortOrder || permission.value.longOrder) {
        // 当前选中的tab，没有默认短租
        let activeTab = listQueryStore.orderActiveTab || 'short-order'
        // 当前选中的为短租，但此时没有短租权限 设置为长租
        if (activeTab == 'short-order' && permission.value.shortOrder == false) {
          activeTab = 'long-order'
          listQueryStore.orderActiveTab = activeTab
        }
        // 第一进入页面 懒加载已加载  当前进入的tab 配置true
        lazyLoadTabs.value[activeTab] = true
      } else {
        console.log('无长短租菜单权限')
      }
    })
  }

  // 局部更新
  const updateOrderItem = () => {
    // 当前操作的订单ID
    const record = uni.getStorageSync('order_operate_record')
    if (record) {
      console.log('需要局部更新的 orderCode:', record.orderCode || record.orderNo)
      if (activeTab.value == 'short-order') {
        shortOrderListRef.value && shortOrderListRef.value.hotUpdate(record)
        return
      }
      longOrderListRef.value && longOrderListRef.value.hotUpdate(record)
    }
  }

  // 加载数据 begin
  // initFectch全部刷新 reachBottom底部加载更多
  const listLoadData = (loadFn = 'initFectch') => {
    lazyLoadTabs.value[activeTab.value] = true
    if (activeTab.value == 'short-order') {
      shortOrderListRef.value && shortOrderListRef.value[loadFn]()
      return
    }
    longOrderListRef.value && longOrderListRef.value[loadFn]()
  }
  onMounted(() => {
    getPermission()
  })
  // 顶部下拉全部刷新
  onPullDownRefresh(() => {
    getPermission()
    listLoadData('initFectch')
  })
  // 底部下拉更多刷新
  onReachBottom(() => {
    listLoadData('reachBottom')
  })
  // 加载数据 end

  useBindEventOn({
    // 整页刷新
    orderLoadData: () => {
      listLoadData()
    },
    // 局部刷新
    orderHotUpdate: () => {
      updateOrderItem()
    },
  })
</script>

<style lang="less" scoped>
  .auth-empty {
    position: fixed;
    top: 50%;
    left: 50%;
    margin-left: -106rpx;
    margin-top: -106rpx !important;
  }
</style>
